package logger;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Calendar;

import main.Agent;
import main.Grid;

public class GameLogger {
	BufferedOutputStream bos;
	FileOutputStream fos;
	OutputStreamWriter osw;
	private static Calendar greg = Calendar.getInstance();
	private static GameLogger instance;
	static boolean success;
	public static GameLogger getInstance(){
		if(instance == null){
			instance = new GameLogger();
		}
		return instance;
	}
	private GameLogger(){
		System.out.println(getFileName());
		System.out.println(System.getProperty("user.dir"));
		File folder =new File(System.getProperty("user.dir")+getFolderName()); 
		if(!folder.exists()){
			success = (folder).mkdir();
		}else{
			success = true;
		}
		try {
			fos = new FileOutputStream(new File(getPath()));
			osw = new OutputStreamWriter(fos, Charset.forName("UTF-8"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			success = false;
		}
		if(success){
			System.out.println("Logger "+((success)? "" : "not") + " ready.");
		}
	}
	
	public void clean(){
		System.out.println("Cleaning logger...");
		try {
			osw.close();
			System.out.println("Logger closed.");
		} catch (IOException e) {
			System.err.println("Cannot close logger");
			e.printStackTrace();
		}
	}
	
	public void logString(String toLog){
		write(toLog);
	}
	public void logNewGame(int gameID){
		logString("\nGame: "+gameID+"\n");
	}
	public void logAgent(Agent agent){
		logString("Player "+((agent.getColorChar() == 'B') ? "Black" : "White")+", "+agent.getName() +"\n");
	}
	public void logGrid(char turn, Grid grid){
		logString(turn+": "+grid.toString() +"\n");
	}
	public void logWinner(Agent winner){
		logString("Player "+((winner.getColorChar() == 'B') ? "Black" : "White")+", "+winner.getName() +", is the winner!\n");
	}
	
	private void write(String toLog) {
		if (success) {
			try {
				osw.write(toLog);
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	private String getPath(){
		String path = System.getProperty("user.dir");
		
		path+=getFileName();
		return path;
	}
	private String getFileName() {
		Calendar cal = Calendar.getInstance();
		
		int hour = greg.get(Calendar.HOUR_OF_DAY);
		int minutes = greg.get(Calendar.MINUTE);
		int seconds = greg.get(Calendar.SECOND);
		return getFolderName()+"\\"+hour+"-"+minutes+"-"+seconds+"_"+getDate();
	}
	private String getFolderName() {
		return "\\Log\\" + getDate();
	}
	private String getDate(){
		int day = greg.get(Calendar.DAY_OF_MONTH);
		int month = greg.get(Calendar.MONTH);
		int year = greg.get(Calendar.YEAR);
		return day+"-"+month+"-"+year;
	}
}
